import json
import random
import re

from django import http
from django.shortcuts import render, redirect, reverse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django_redis import get_redis_connection

from libs.aliyu.send_sms import send_sms
from libs.capt.captcha import captcha
from celery import Celery

from utils import constants

app = Celery(broker='amqp://guest@localhost//')  # 消息队列的url


class Imgcode(View):
    def get(self, request):
        uuid = request.GET.get("code_id")
        _, text, img = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)
        print("1", uuid, text)
        return http.HttpResponse(img, content_type="image/png")

@method_decorator(csrf_exempt, name="dispatch")
class Sms_code(View):
    def post(self, request):
        # 提取数据
        data = json.loads(request.body.decode("utf-8"))
        uuid = data.get("uuid")
        print("123", uuid)
        image_code = data.get("image_code")
        # 连接redis数据库
        redis_conn = get_redis_connection('code')
        t_f = redis_conn.get("img_%s" % uuid)
        mobile = data.get("phone")

        phone = redis_conn.get("phone_code_%s" % mobile)
        if not all([uuid, image_code, mobile]):
            return http.JsonResponse({'code': "201", 'errmsg': '缺少参数'})
        if not re.search(r"^1[3-9]\d{9}$", mobile):
            return http.JsonResponse({'code': "208", 'errmsg': '手机号错误'})
        if phone:  # 防止手机号重复注册
            return http.JsonResponse({'code': "202", 'errmsg': '操作频繁'})
        # 连接redis数据库
        redis_conn = get_redis_connection('code')
        # 提取验证码
        t_f = redis_conn.get("img_%s" % uuid)
        if not t_f:
            return http.JsonResponse({'code': "404", 'errmsg': '图片验证码已过期'})
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            print(e)
        print(t_f.decode().lower(), image_code.lower())
        if t_f.decode().lower() != image_code.lower():
            return http.JsonResponse({'code': "200", 'errmsg': '验证码错误'})
        sms_code = '%06d' % random.randint(0, 999999)

        redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        send_sms(mobile, sms_code)
        print(">>>>短信验证码>>>>>>", sms_code)
        return http.JsonResponse({'code': "0", 'errmsg': '手机验证码发送成功'})
